package com.baidu.jiuhao.es.service;

import com.baidu.jiuhao.es.req.FaqSearchRequest;
import com.baidu.jiuhao.es.rsp.FaqSearchResponse;
import com.baidu.jiuhao.es.util.EsUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;


@Service
@RequiredArgsConstructor
@Slf4j
public class SearchFaqervice {

    /**
     * faq检索。
     *
     * @param request
     * @return
     */
    public FaqSearchResponse searchFaqs(FaqSearchRequest request) {
        // 将索引列表转换为数组
        // 检查索引是否存在
        /*EsUtils.checkIndicesExist(client, arrayIndex);*/
        // 创建搜索请求
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indicesOptions(IndicesOptions.lenientExpandOpen()); // 忽略不存在的索引
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        // 创建布尔查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 添加全文检索条件
        if (request.getKeyword() != null && !request.getKeyword().isEmpty()) {
            boolQuery.must(QueryBuilders.matchPhraseQuery("tokenized_word", request.getKeyword()));
        }

        // 添加agent_id过滤条件
        BoolQueryBuilder agentFilter = QueryBuilders.boolQuery();
        if (request.getAgentId() != null && !request.getAgentId().isEmpty()) {
            agentFilter.should(QueryBuilders.termQuery("agent_id", request.getAgentId()));
        }
        if (request.getPublicAgent() != null && request.getPublicAgent()) {
            agentFilter.should(QueryBuilders.termQuery("agent_id", "公共知识库agent_id"));
        }
        if (!agentFilter.should().isEmpty()) {
            agentFilter.minimumShouldMatch(1);
            boolQuery.filter(agentFilter);
        }

        // 添加其他可选过滤条件
        if (request.getDirId() != null && !request.getDirId().isEmpty()) {
            boolQuery.filter(QueryBuilders.termQuery("dir_id", request.getDirId()));
        }
        if (request.getVersion() != null && !request.getVersion().isEmpty()) {
            boolQuery.filter(QueryBuilders.termQuery("version", request.getVersion()));
        }
        if (request.getLabels() != null && !request.getLabels().isEmpty()) {
            boolQuery.filter(QueryBuilders.termsQuery("label", request.getLabels()));
        }
        if (request.getAvailable() != null) {
            boolQuery.filter(QueryBuilders.termQuery("enable", request.getAvailable()));
        }

        sourceBuilder.query(boolQuery);

        // 设置分页
        sourceBuilder.from((request.getPageNum() - 1) * request.getPageSize());
        sourceBuilder.size(request.getPageSize());

        // 设置排序
        sourceBuilder.sort(SortBuilders.scoreSort().order(SortOrder.DESC));

        // 排除 tokenized_word 字段，保留其他所有字段
        sourceBuilder.fetchSource(
                null,  // null 表示包含所有字段
                new String[]{"vector"}  // 排除指定字段
        );

        searchRequest.source(sourceBuilder);

        // 打印 DSL
        log.info("----- Generated DSL -----");
        EsUtils.printPrettyDSL(sourceBuilder.toString());

        return new FaqSearchResponse();

        /*try {
            // 执行搜索请求
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            FaqSearchResponse response = new FaqSearchResponse();
            response.setTotal(searchResponse.getHits().getTotalHits().value);

            // 处理搜索结果
            List<Map<String, Object>> faqs = new ArrayList<>();
            for (SearchHit hit : searchResponse.getHits().getHits()) {
                faqs.add(hit.getSourceAsMap());
            }

            response.setFaqs(faqs);
            return response;
        } catch (IOException e) {
            throw new RuntimeException("Error while searching FAQs", e);
        }*/
    }
}
